package com.lizk.study.netty.utils;

import com.lizk.study.netty.entity.ClientContent;
import com.lizk.study.netty.entity.ServerContent;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;

/**
 * @author lizhikui
 * @date 2019/6/15 15:27
 */
public class NettyUtils {
    public static ServerContent createServerContent(Class clazz){
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup).channel(clazz);
        ServerContent serverContent = new ServerContent();
        serverContent.setBossGroup(bossGroup);
        serverContent.setWorkerGroup(workerGroup);
        serverContent.setServerBootstrap(serverBootstrap);
        return serverContent;
    }

    public static void stop(ServerContent serverContent){
        serverContent.getBossGroup().shutdownGracefully();
        serverContent.getWorkerGroup().shutdownGracefully();
    }

    public static ChannelFuture bind(ServerContent content,int port) throws InterruptedException {
        ChannelFuture channelFuture = content.getServerBootstrap().bind(9999).sync();
        channelFuture.channel().closeFuture().sync();
        return channelFuture;
    }

    public static ClientContent createClientContent(Class clazz){
        EventLoopGroup mainGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(mainGroup)
        .channel(clazz);

        ClientContent clientContent = new ClientContent();
        clientContent.setBootstrap(bootstrap);
        clientContent.setMainGroup(mainGroup);
        return clientContent;
    }


    public static ChannelFuture conn(ClientContent clientContent,String ip,int port) throws InterruptedException {
        ChannelFuture channelFuture = clientContent.getBootstrap().connect(ip, port).sync();
        channelFuture.channel().closeFuture().sync();
        return channelFuture;
    }

    public static void stop(ClientContent clientContent){
        clientContent.getMainGroup().shutdownGracefully();
    }


}
